import { reactive, ref, watch } from 'vue'
import TargetClient from '@/api/targetClient.js'
import store from '@/store'
export function useAddNewOrganization(addOrganizationFormRef, dict, apiData) {
  const showAddOrganization = ref(false)
  const buttonLoading = ref(false)
  watch(
    () => showAddOrganization.value,
    () => {
      organizationFormForAdd.name = ''
    }
  )
  const organizationFormForAdd = reactive({
    name: ''
  })
  const addOrganizationRules = [
    {
      required: true,
      whitespace: true,
      message: 'Please input organization name',
      trigger: 'blur'
    }
  ]
  const tempOrganizations = reactive([])
  const handleAddOrganization = () => {
    addOrganizationFormRef.value.validate().then(() => {
      buttonLoading.value = true
      TargetClient.createOrganization(organizationFormForAdd.name)
        .then(({ data }) => {
          store.dispatch('dict/getOrganizations', true).then(() => {
            apiData.ParentID ? (apiData.ParentID = data) : (apiData.parentID = data)
          })
        })
        .finally(() => {
          buttonLoading.value = false
          showAddOrganization.value = false
        })
    })
  }

  return {
    organizationFormForAdd,
    tempOrganizations,
    showAddOrganization,
    addOrganizationRules,
    buttonLoading,
    handleAddOrganization
  }
}
